/*
 * =====================================================================================
 *
 *       Filename:  fd.c
 *
 *    Description:  测试libubox fd
 *
 *        Version:  1.0
 *        Created:  2019年09月10日 11时56分15秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "uloop.h"


/* 实现一个udp回射服务器 */
void my_cb(struct uloop_fd *fd, unsigned int events)
{
    if(!(events & ULOOP_READ)) {
        printf("Not a read event\n");
        return;
    }
    struct sockaddr remote;
    socklen_t len_remote;
    char buff[1024]  ={0};
    int ret = recvfrom(fd->fd, buff, 1024, 0, &remote, &len_remote);
    if(ret >= 0) {
        printf("recvfrom: %s\n", buff);
        sendto(fd->fd, buff, ret, 0, &remote, len_remote);
    }
}


int main(int argc, char **argv)
{
    /* 建立udp回射服务器监听套接字 */
    int fd_udp = socket(AF_INET, SOCK_DGRAM, 0);
    if(fd_udp < 0) {
        perror("socket()");
        return 0;
    }
    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = inet_addr("0.0.0.0");
    local.sin_port = htons(12345);
    bind(fd_udp, (struct sockaddr *)&local, sizeof(local));

    /* ①事件循环初始化 */ 
    if(uloop_init() < 0) {
        printf("uloop_init failed\n");
        return 0;
    }
    struct uloop_fd *fd = (struct uloop_fd *)calloc(1, sizeof(*fd));
    if(NULL == fd) {
        perror("calloc()");
        goto this_exit;
    }
    fd->fd = fd_udp; 
    fd->cb = my_cb;
    uloop_fd_add(fd, ULOOP_READ);
    uloop_run();

this_exit:
    uloop_done();
    close(fd_udp);
    return 0;
}


